package com.dylovedz.javafxphone.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.dylovedz.javafxphone.domain.LastOpenFile;
import com.dylovedz.javafxphone.domain.WechatApp;
import com.dylovedz.javafxphone.service.*;
import de.felixroske.jfxsupport.FXMLController;
import javafx.event.ActionEvent;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.layout.Pane;
import javafx.stage.DirectoryChooser;
import javafx.stage.Window;
import javafx.util.StringConverter;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.io.File;
import java.net.URL;
import java.util.*;

/**
 * 主界面控制器
 *
 * @author dylovedz
 * @date 2023/03/09 16:50
 */
@Slf4j
@FXMLController
public class WechatController implements Initializable {

    public Button btnCancel;
    @Resource
    LastOpenFileService lastOpenFileService;

    @Resource
    WechatAppService wechatAppService;

    public ComboBox<WechatApp> appIdSelect;

    public CheckBox rememberMe;

    public ProgressBar exportPro;
    // 主容器
    public Pane wechatPane;
    @Autowired
    private WechatService wechatService;

    public Button btnSearch;
    public TextArea phoneGeoText;
    public Button btnChooseDir;
    public Tooltip btnChooseDirTip;
    public TextField appIdText;
    public TextField appSecretText;

    private String outDir;
    private File lastFile;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        // 查询记住AppID
        List<WechatApp> appList = wechatAppService.findAll();
        appIdSelect.getItems().addAll(appList);
        appIdSelect.setConverter(new StringConverter<WechatApp>() {
            @Override
            public String toString(WechatApp object) {
                if (ObjectUtil.isNotNull(object)) {
                    return object.getAppId();
                }
                return null;
            }

            @Override
            public WechatApp fromString(String string) {
                WechatApp fm = new WechatApp();
                fm.setAppId(string);
                return fm;
            }
        });
        // 查询
        LastOpenFile lastPath = lastOpenFileService.findById(1);
        if (lastPath.getLastPath() != null) {
            lastFile = FileUtil.file(lastPath.getLastPath());
        }
        log.info("initialize: {}", location.getPath());
    }

    /**
     * 查询公众号信息
     * @param actionEvent
     */
    public void onBtnSearchClick(ActionEvent actionEvent) {
        String appid = appIdSelect.editorProperty().get().getText();
        String appSecret = appSecretText.getText();
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        if (StrUtil.isBlank(appid)) {
            alert.setContentText("请输入appId");
            alert.show();
            return;
        }

        if (StrUtil.isBlank(appSecret)) {
            alert.setContentText("请输入appSecret");
            alert.show();
            return;
        }

        if (StrUtil.isBlank(outDir)) {
            alert.setContentText("请选择导出目录");
            alert.show();
            return;
        }

        try {
            WxMpServiceImpl wxMpService = new WxMpServiceImpl();
            WxMpDefaultConfigImpl wxMpDefaultConfig = new WxMpDefaultConfigImpl();
            wxMpDefaultConfig.setAppId(appid);
            wxMpDefaultConfig.setSecret(appSecret);
            wxMpService.setWxMpConfigStorage(wxMpDefaultConfig);

            MaterialRunTask task = new MaterialRunTask(wxMpService, wechatService, outDir);
            Thread thread = new Thread(task);
            thread.start();

            btnCancel.setOnAction(event -> {
                task.cancel();
            });

            task.progressProperty().addListener((observable, oldValue, newValue) -> {
                exportPro.setProgress((Double) newValue);
            });
            task.messageProperty().addListener((observable, oldValue, newValue) -> {
                phoneGeoText.setText(newValue);
            });

            // 保存公众号信息
            if (rememberMe.isSelected()) {
                WechatApp res = wechatAppService.save(appid, appSecret);
                appIdSelect.getItems().add(res);
            }

        } catch (Exception exception) {
            phoneGeoText.setText("程序异常：" + exception.getMessage());
        }
    }

    /**
     * 选择导出目录
     * @param actionEvent
     */
    public void onBtnChooseDirClick(ActionEvent actionEvent) {
        Window window = wechatPane.getScene().getWindow();
        DirectoryChooser folderChooser = new DirectoryChooser();
        if (ObjectUtil.isNotNull(lastFile)) {
            folderChooser.setInitialDirectory(lastFile);
        }
        // ...
        File file = folderChooser.showDialog(window);
        String fileName = file == null ? "" : file.getName();
        String fileAbsolutePath = file == null ? "" : file.getAbsolutePath();
        if (file != null) {
            btnChooseDir.setText(fileAbsolutePath);
            btnChooseDirTip.setText(fileAbsolutePath);
            outDir = fileAbsolutePath;
            lastFile = file;
            lastOpenFileService.saveOrUpdateById(1, fileAbsolutePath);
            /*Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setContentText("文件路径：" + fileAbsolutePath);
            alert.show();*/
        }
    }

    public void onBtnRememberMe(ActionEvent actionEvent) {

    }

    public void onSelectAppId(ActionEvent actionEvent) {
        SingleSelectionModel<WechatApp> selectionModel = appIdSelect.getSelectionModel();

        if (selectionModel != null && selectionModel.getSelectedIndex() >= 0) {
            if (selectionModel.getSelectedItem().getAppSecret() != null) {
                appSecretText.setText(selectionModel.getSelectedItem().getAppSecret());
            }
        }
    }
}
